/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rw.table;

import com.rw.table.editor.ICellEditor;
import com.rw.table.formatter.ICellFormatter;
import com.rw.table.render.ICellRenderer;
import java.awt.Color;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Rene Tapia
 */
public abstract class ATableModel extends AbstractTableModel {

    public abstract ICellRenderer getRenderer(int row, int column);

    public abstract ICellEditor getEditor(int row, int column);

    public abstract ICellFormatter getFormatter(int row, int column);

    public abstract ATableAction getEditableByClickAction(int row, int col);

    @Override
    public abstract void setValueAt(Object value, int rowIndex, int columnIndex);

    @Override
    public abstract String getColumnName(int column);

    public ATableModel() {
    }

    @Override
    public boolean isCellEditable(int row, int column) {
        ICellEditor editor = getEditor(row, column);
        if (editor != null) {
            boolean editableByClick = getRenderer(row, column).isEditableByClick();
            if (editableByClick) {
                throw new RuntimeException("La celda [" + row + ", " + column + "] posee renderizador y ademas es editable por click");
            }
            return true;
        } else {
            return false;
        }
    }

    public Color getBackground(int row, int column) {
        return null;
    }

    public boolean isCellEditableByClick(int row, int column) {
        boolean editableByClick = getRenderer(row, column).isEditableByClick();
        if (editableByClick) {
            boolean gotEditor = getEditor(row, column) != null;
            if (gotEditor) {
                throw new RuntimeException("La celda [" + row + ", " + column + "] posee editor y ademas es editable por click");
            }
            return true;
        } else {
            return false;
        }
    }

    public void configure(JTable table, EditionStyle style) {
        table.setDefaultRenderer(Object.class, new TableRenderer());
        TableEditor tableEditor = new TableEditor(style);
        table.setDefaultEditor(Object.class, tableEditor);
        table.addMouseListener(new TableMouseListener(table));
        table.addMouseMotionListener(new TableMouseMotionListener(table));

        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        table.setCellSelectionEnabled(true);

        int n = getRowCount();
        int m = getColumnCount();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                ICellEditor editor = getEditor(i, j);
                if (editor != null) {
                    editor.setTableEditor(tableEditor);
                }
            }
        }
    }
}
